import {reactive} from 'vue'
import router from "@/router/routers";
import {ElMessage} from 'element-plus'
import {getUserInfo as getUserInfoApi, login as loginApi,} from '@/api/user'

// vuex的ts类型定义很麻烦，组合式api的话，不集中到一个store里也可以很方便的做响应式
export const userInfo = reactive<any>({
  data: null,
});

function storeCookie(resp: any) {
  if (resp.code !== 200) {
    ElMessage.error(resp.message);
    return
  }
  let data = resp.data;
  // cacheConfig(data)
  delete data.token;
  userInfo.data = data;


  return data;
}

export class Loading {
  private readonly loadingElement: HTMLDivElement;
  private animate: Animation;

  constructor() {
    let loadingElement = document.createElement('div');
    loadingElement.style.position = 'fixed';
    loadingElement.style.left = '0px';
    loadingElement.style.top = '0px';
    loadingElement.style.bottom = '0px';
    loadingElement.style.right = '0px';
    loadingElement.style.width = '100%';
    loadingElement.style.height = '100%';
    // loadingElement.style.lineHeight = '50';
    loadingElement.style.color = '#0cf0f3';
    // loadingElement.style.display = 'none';
    loadingElement.style.textAlign = 'center';
    loadingElement.style.setProperty('align-items', 'center');
    loadingElement.style.background = 'rgba(22,67,75,1)';
    loadingElement.style.zIndex = '10000';

    // loadingElement.style.transition = 'all .2s';
    // loadingElement.innerText = "系统加载中..."
    loadingElement.innerHTML = "<div style='width: 100%;height:100%;line-height:50;font-size: 18px;font-weight: bolder;letter-spacing: 3px;' class='animate__animated animate__pulse animate__infinite'>系统加载中...</div>"
    this.loadingElement = loadingElement;
    this.animate = loadingElement.animate(
      [
        {opacity: "1", offset: 0},
        {opacity: "0", offset: 1},
      ],
      {
        duration: 300
      }
    )
    this.animate.cancel()
    this.animate.onfinish = () => {
      loadingElement.remove()
    }

    // document.body.appendChild(loadingElement);
  }

  start() {
    document.body.appendChild(this.loadingElement);
  }

  close() {
    // this.loadingElement.style.display = 'none';
    this.animate.play();
    // setTimeout(() => {
    // }, 200)

    // if (this.loadingElement){
    //   document.body.removeChild(this.loadingElement);
    // }
  }

}

export const loading = new Loading();
// loading.start()

export const login = async (data: any, uid: string) => {
  let params: any = {
    userName: data.userName,
    // password: jsEncrypt.encrypt(data.password) as string,
    verifyCode: data.verifyCode
  }
  return new Promise<void>((resolve, reject) => {
    loginApi(params)
      .then((resp: any) => {
        let data = storeCookie(resp);
        if (data) {
          let path = router.currentRoute.value.redirectedFrom?.fullPath || '/';
          router.replace({
            path: path,
          })
            .then(r => {
            })
            .catch(e => {
              console.error(e.message)
            })
          resolve();
        } else {
          reject()
        }
      })
      .catch((e: Error) => {
        ElMessage.error(e)
        reject()
      })
  })
}

export const getUserInfo = () => {
  return new Promise<void>((resolve, reject) => {
    getUserInfoApi()
      .then((resp: any) => {
        let data = storeCookie(resp);
        if (data) {
          resolve(data);
        } else {
          reject()
        }
      })
      .catch((e: Error) => {
        if (e && e.message) {
          ElMessage.error(e.message)
        }
        reject()
      })
  })

}

export const toLogin = () => {
  localStorage.clear();
  //有多个接口请求的时候只走一次路由重定向
  if (router.currentRoute.value.path !== '/login') {
    router.replace({
      path: '/login',
      query: {redirect: router.currentRoute.value.fullPath}
    })
      .then(r => {
      })
      .catch(e => {
        console.error(e.message)
      })
  }
}

export const logout = () => {
  // logoutApi()
  //   .then((resp: any) => {
  //     if (resp.code === 200) {
  //       toLogin();
  //     }
  //   })
}
